<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            思路：先将nums从小到大进行排序，然后把所有负数弄正，k--

            */
            var largestSumAfterKNegations = function (nums, k) {
                nums.sort((a, b) => a - b)
                for (let i = 0; i < nums.length; i++) {
                    if (nums[i] <= 0 && k > 0) {
                        nums[i] = -nums[i]
                        k--
                    }
                }
                /* 
                负数翻转完以后，k还存在且不为奇数,只需要让头部元素变为负数即可
                偶数直接不用考虑了
                */
                if (k > 0 && k % 2 != 0) {
                    nums.sort((a, b) => a - b)
                    nums[0] = -nums[0]
                }
                return nums.reduce((a, b) => (a += b))
            }
        </script>
    </body>
</html>
